<?php
/*
Author: Khoiruddin
Semoga bermanfaat
helper ini otomatis dipanggil jika menggunakan library Smartup
*/
if (!function_exists('dndImage')) {
  function dndImage() {
?>
      <!-- pick image modal -->
      <div class="modal modal-xl" id="pickImage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="myModalLabel">Pilih Gambar</h4>

              <div style="position:absolute;top:18px;left:135px;">
                <div class="radio radio-primary radio-inline">
                    <input type="radio" name="pilihan" id="unggah" checked/>
                    <label for="unggah">
                      Unggah
                    </label>
                </div>
                <div class="radio radio-primary radio-inline">
                    <input type="radio" name="pilihan" id="dariweb"/>
                    <label for="dariweb">
                      Dari web ini
                    </label>
                </div>
              </div>

            </div>
            
            <div class="modal-body" style="min-height:430px;position:relative;">
            
            <div id="unggaharea">
            <?=form_open_multipart('media/image_upload', array('id' => 'image_upload'));?>

              <div align="center" id="proses" class="progress active" style="margin-top:185px;display:none;">
                <div class="progress-bar progress-bar-striped progress-bar-aqua" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
                  <span class="percent">0% Complete</span>
                </div>
              </div>

              <div id="gagal" style="display:none;position:absolute;top:200px;left:410px;"><i class="fa fa-times-circle"></i> Maaf, gagal mengunggah...</div>
              <div id="pick-button" class="btn-pick-image-modal-center">
                <input type="file" accept="image/x-png, image/gif, image/jpeg" name="image_file" class="filestyle" data-iconName="fa fa-cloud-upload" data-badge="false" data-buttonText="&nbsp;&nbsp;Ambil dari komputer" data-buttonName="btn-default btn-flat" data-input="false">
              </div>          
            <?=form_close();?>
            </div>

            <div id="dariwebarea" style="display:none;">
              
            </div>

            <?=form_open_multipart('media/image_crop', array('id' => 'image_crop'));?>
            <span class="dynamic-image"></span>

            <input type="hidden" name="dataX" id="dataX">
            <input type="hidden" name="dataY" id="dataY">
            <input type="hidden" name="dataHeight" id="dataHeight">
            <input type="hidden" name="dataWidth" id="dataWidth">

            </div>
            <div class="modal-footer">
              <button disabled type="button" id="reset" class="reset btn btn-default btn-flat">Reset</button>
              <button type="button" id="batal" class="btn btn-default btn-flat" data-dismiss="modal">Batal</button>
              <button disabled type="submit" id="simpan" class="btn btn-primary btn-flat"><i class="simpanIcon fa fa-floppy-o"></i>  Simpan</button>
            </div>
            <?=form_close();?>
          </div>
        </div>
      </div>

      <!-- remove modal -->
      <div class="modal modal-s" id="removeImage" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel" style="color:red;font-weight:bold;">Copot Gambar</h4>
          </div>
          <div class="modal-body" style="position:relative;">       
          <img id="crop_result_delete" src="" width="100" />
          <span style="position:absolute;left:150px;top:45px;">
          <p>Yakin ingin mencopot gambar ini ? Gambar ini akan tetap ada di <a href="<?=site_url('media')?>">Pustaka Media</a></p>
          </span>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default btn-flat" data-dismiss="modal">Batal</button>
            <button type="submit" id="copot" class="btn btn-danger btn-flat"><i class="fa fa-exclamation-triangle"></i>&nbsp;Copot</button>
          </div>
        </div>
      </div>
    </div>

    <div class="box-body">
      <div class="wrap">

      <span style="position:relative;">
      <div id="kotak_1" style="position:relative;" class="kotak-sm" data-toggle="modal" data-target="#pickImage" onClick="uniquePick(1); uniqueRemove(1);">
        <div class="kotakInner">        
          <img id="crop_result_1" src="<?=base_url('themes/back/img/default.png')?>" />
          <div class="titlekotak"><span id="tooltext_1">Pilih gambar</span></div>
          <input name="imagefile[]" type="hidden" id="gambar_1">
        </div>
      </div>

      <select name="status[]" class="form-control" style="position:absolute;top:132px;left:-131px;width:126px;">
        <option value="salah" selected>Salah</option>
        <option value="benar">Benar</option>
      </select> 
      </span>

      <span id="additional"></span>
      <button id="tambah" style="float:left;margin-top:55px;margin-left:20px;cursor:pointer;" class="btn btn-flat btn-primary btn-sm" title="Tambah gambar lagi"><i class="fa fa-plus-circle"></i></button>

      </div>      
    </div>

    <script>
    function basename(path) {
      return path.replace(/\\/g,'/').replace( /.*\//, '' );
    }
     
    function dirname(path) {
      return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');;
    }

    $(document).ready(function() {
        var max_fields      = 5; //maximum input boxes allowed
        var wrapper         = $("#additional"); //Fields wrapper
        var add_button      = $("#tambah"); //Add button ID
        
        var x = 1; //initlal text box count
        var y = 2;
        var z = 2;
        var a = 2;
        var b = 2;
        var c = 2;
        var d = 2;
        $(add_button).click(function(event){ //on add input button click
            event.preventDefault();
            if(x < max_fields){ //max input box allowed
                x++; //text box increment
                $(wrapper).append('<span style="position:relative;"><div id="kotak_'+ c++ +'" style="position:relative;" class="kotak-sm" data-toggle="modal" data-target="#pickImage" onclick="uniquePick('+ y++ +'); uniqueRemove('+ d++ +');"><span style="position:absolute;top:5px;right:5px;background:#ff4444;opacity:0.7;width:20px;height:20px;z-index:100;padding-left:4px;color:#fff;" id="remove_field" title="Hapus ini"><i class="fa fa-times"></i></span><div class="kotakInner"><img id="crop_result_'+ z++ +'" src="<?=base_url('themes/back/img/default.png')?>" /><div class="titlekotak"><span id="tooltext_'+ b++ +'">Pilih gambar</span></div><input name="imagefile[]" type="hidden" id="gambar_'+ a++ +'"></div></div><select name="status[]" class="form-control"style="position:absolute;top:132px;left:-131px;width:126px;"><option value="salah" selected>Salah</option><option value="benar">Benar</option></select></span>'); //add input box             
            }; 

        });

        $(wrapper).on("click","#remove_field", function(e){ //user click on remove text
            e.preventDefault(); e.stopPropagation(); $(this).parent('div').remove(); x--;
        })   
        
    });

    //radio pilih gambar unggah atau dari web
    $('#unggah').change(
      function(){
        $('#unggaharea').show();
        $('#dariwebarea').hide();
      }
    );

    $('#dariweb').change(
      function(){
        $('#unggaharea').hide();
        $('#dariwebarea').show();

        $('.jqload').show();
        $("#dariwebarea").load("<?php echo site_url('media/list_image');?>", function() {
            $('.jqload').hide();
        });
      }
    );

    //unggah dari lokal      
    $('input[name=image_file]').change(function() { 
      var bar     = $('.progress-bar');
      var percent = $('.percent');
        $('#image_upload').ajaxForm({
          beforeSend: function() {
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);

            $("#pick-button").hide();
            $("#proses").show();
            $("#gagal").hide();
            $("#simpan").attr("disabled","disabled");
            $("#reset").attr("disabled","disabled");
            $("#batal").attr("disabled","disabled");
          },
          uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal)
            percent.html(percentVal);
          },
          success: function(response) {
            var percentVal = '100%';
            bar.width(percentVal)
            percent.html(percentVal);

            $('.dynamic-image').html(response);
            $('#pick-button').removeClass('btn-pick-image-modal-center');  
            $('#pick-button').addClass('btn-pick-image-modal-bottom');
            $("#pick-button").show();
            $("#proses").hide();
            $("#gagal").hide();
            $("#simpan").removeAttr("disabled");
            $("#reset").removeAttr("disabled");
            $("#batal").removeAttr("disabled");
          },
          error: function() {
            $('#pick-button').removeClass('btn-pick-image-modal-center');  
            $('#pick-button').addClass('btn-pick-image-modal-bottom');
            $("#pick-button").show();
            $("#proses").hide();
            $("#gagal").show();
            $("#batal").removeAttr("disabled");
          }
        }).submit();
    });
    
    //menjadikan unik pada setiap modal copot gambar
    function uniqueRemove(id){
      var img_src = $('#crop_result_' + id).attr('src');
      $('#crop_result_delete').attr('src', img_src);
      $('#copot').attr('onClick','copot('+ id +')');
    }

    //copot gambar dari kotakan
    function copot(id){
      $('#removeImage').modal('hide');
      $("#crop_result_" + id).attr("src", '');
      $("#crop_result_delete").attr("src", '');
      $("#gambar_" + id).val('');
      $("#tooltext_" + id).text('Pilih gambar');
    };
    //menjadikan unik pada setiap modal pilih gambar
    function uniquePick(id){
      //crop yang telah diunggah
      $('#image_crop').ajaxForm({
        beforeSend: function() {
          $("#simpan").attr("disabled","disabled");
          $("#reset").attr("disabled","disabled");
          $("#batal").attr("disabled","disabled");
          $('.simpanIcon').removeClass('fa-floppy-o').addClass('fa-circle-o-notch fa-spin');
        },
        success: function(response) {
          $("#crop_result_" + id).attr("src", response);
          $("#gambar_" + id).val(basename(response));
          $("#tooltext_" + id).text('Copot gambar');
          $("#kotak_" + id).attr('data-target','#removeImage');

          $('#pickImage').modal('hide')
          $('.simpanIcon').removeClass('fa-circle-o-notch fa-spin').addClass('fa-floppy-o');
        },
        error: function() {
          $("#batal").removeAttr("disabled");
          $('.simpanIcon').removeClass('fa-circle-o-notch fa-spin').addClass('fa-floppy-o');
        }
      });
    }    

    //ketika modal ditutup
    $('#pickImage').on('hidden.bs.modal', function (e) {
        $('.dynamic-image').html('');
        $('#pick-button').removeClass('btn-pick-image-modal-bottom');
        $('#pick-button').addClass('btn-pick-image-modal-center');
        $("#simpan").attr("disabled","disabled");
        $("#reset").attr("disabled","disabled");
        $("#batal").attr("disabled","disabled");        
    });       

    //setelah ajax selesai di load
    $(document).ajaxComplete(function(){

      //ambil posisi crop
      var $image = $(".dynamic-image img"),
          $dataX = $("#dataX"),
          $dataY = $("#dataY"),
          $dataHeight = $("#dataHeight"),
          $dataWidth = $("#dataWidth");

      $image.cropper({
        aspectRatio: 1,
        minContainerWidth:980,
        minContainerHeight:400,
        done: function(data) {
          $dataX.val(data.x);
          $dataY.val(data.y);
          $dataHeight.val(data.height);
          $dataWidth.val(data.width);
        }
      });

      //reset crop
      $(".reset").click(function() {
        $image.cropper("reset");
      });
    });

    </script>     
    <?php
  }
}